layui.form.verify({
  articleTitle: [
    /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
    "标题只能是中英文, 数字下划线中划线组成",
  ],
  // 分类判断
  cate: function () {
    return $("select[name=cate_id]").val().length == 0 && "请选择文章类别";
  },
});

//渲染
function render() {
  axios({
    method: "GET",
    url: "http://api-breakingnews-web.itheima.net/my/article/cates",
    headers: {
      //给后端转的自定义请求头
      Authorization: localStorage.getItem("token"),
    },
  }).then(({ data: res }) => {
    // console.log(res);
    //判断请求成功
    if (res.status === 0) {
      res.data.forEach((obj) => {
        const theOpt = $(
          `<option value="${obj.Id}" lay-verify="cate">${obj.name}</option>`
        );
        $('select[name="cate_id"]').append(theOpt);
      });
      //遍历结束之后渲染
      layui.form.render("select", "edit");
    }
  });
}
render();
let imgUrl = "";
//上传图片
$(".select").on("click", function () {
  $("#file").click();
});

$("#file").on("change", function (e) {
  const files = e.target.files;
  //   console.log(files);
  if (files.length === 0) return;
  const blobUrl = window.URL.createObjectURL(files[0]);
  //将生产的blob 替换页面中img的src
  $("#image").prop("src", blobUrl);
  imgUrl = files[0];
});

$("form").on("submit", function (e) {
  e.preventDefault();
  // const fd =new FormData(参数)
  const htmlStr = tinyMCE.activeEditor.getContent();
  const fd = new FormData($("form")[0]);
  fd.set("content", htmlStr);
  fd.append("cover_img", imgUrl);
  // console.log(fd);
  // fd.forEach((value, key) => {
  //   console.log("value,key", value, key);
  // });
  axios({
    method: "POST",
    url: "http://api-breakingnews-web.itheima.net/my/article/add",

    headers: {
      //给后端转的自定义请求头
      Authorization: localStorage.getItem("token"),
    },
    data: fd,
  }).then(({ data: res }) => {
    console.log(res);
    //判断请求成功
    layer.msg(res.message);
    if (res.status === 0) {
      window.parent.$("#wzlist a").click();
      location.href = "./../list/list.html";
    }
  });
});

//初始化富文本编辑器
initEditor();
